//
//  ShopListViewController.m
//  OrderSeat
//
//  Created by wangwei on 13-10-7.
//  Copyright (c) 2013年 wangwei. All rights reserved.
//

#import "ShopListViewController.h"
#import "ShopHomeViewController.h"
#import "SearchShopViewController.h"
#import "ShopInfoCell.h"
#import "SVProgressHUD.h"

@interface ShopListViewController ()

@property (nonatomic, strong) SelectCuisinesView *selectCuisinesView;
@property (nonatomic, strong) SelectCircleView *selectCircleView;
@property (nonatomic, strong) SelectOrderView *selectOrderView;

@property (nonatomic, strong) NSString *cuisinesId;
@property (nonatomic, strong) NSString *circleId;
@property (nonatomic, strong) NSString *orderId;

@end

@implementation ShopListViewController

- (id)init
{
    self = [super initWithNibClass:[ShopListViewController class]];
    if (self) {
        //默认菜系、商圈、排序都为空
        _cuisinesId = _circleId = _orderId = S_EMPTY;
        _dataSource = [[ShopListDataSource alloc] initWithVC:self];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self setupUI];
    
    [[BaseDataManager sharedInstance] startDownLoad];
}

#pragma 隐藏tabbar
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [[AppDelegate sharedInstance] hideTabBar:self.tabBarController];
    
    //获取餐厅列表
    [_dataSource fetchShopWithCuisines:S_EMPTY circle:S_EMPTY order:S_EMPTY isLoadMore:NO];
}

#pragma 初始化UI
- (void)setupUI
{
    [self createLeftButton];
    [self createNavigation:@"餐厅列表"];
    [self createRightButtonWithTitle:S_EMPTY background:NAV_SEARCH_BACKGROUND frame:CGRectMake(0, 0, 30, 30)];
    
    [self setupToolsView];
    
    self.shopTable.delegate = self.dataSource;
    self.shopTable.dataSource = self.dataSource;
}

#pragma 返回按钮事件
- (void)leftButtonClick:(id)sender
{
    [AppDelegate changeToNormalTabBar];
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)rightButtonClick:(id)sender
{
    SearchShopViewController *searchVC = [[SearchShopViewController alloc] init];
    [self pushViewController:searchVC];
}

#pragma 添加选择菜系、地区和排序视图
- (void)setupToolsView
{
    _selectCuisinesView = [[SelectCuisinesView alloc] initWithFrame:CGRectMake_V7(0, 46, ScreenWidth, 0)];
    _selectCuisinesView.delegate = self;
    [self.view addSubview:_selectCuisinesView];
   
    _selectCircleView = [[SelectCircleView alloc] initWithFrame:CGRectMake_V7(0, 46, ScreenWidth, 0)];
    _selectCircleView.delegate = self;
    [self.view addSubview:_selectCircleView];
    
    _selectOrderView = [[SelectOrderView alloc] initWithFrame:CGRectMake_V7(0, 46, ScreenWidth, 0)];
    _selectOrderView.delegate = self;
    [self.view addSubview:_selectOrderView];
}

#pragma 弹出选择菜系菜单
- (IBAction)selectCuisinesAction:(id)sender
{
    [_selectCuisinesView showOrVisible];
    [_selectCircleView hidden];
    [_selectOrderView hidden];
}

#pragma 选择菜系选项
- (void)selectCuisinesFinished:(NSDictionary *)selectedData
{
    NSString *title = [selectedData objectForKey:@"lx_name"];
    _cuisinesId = [selectedData objectForKey:@"id"];
    
    [self.toolButton1 setTitleForNormal:title];
    
    [_dataSource fetchShopWithCuisines:_cuisinesId circle:_circleId order:_orderId isLoadMore:NO];
}

#pragma 弹出选择商圈菜单
- (IBAction)selectedAreaAction:(id)sender
{
    [_selectCircleView showOrVisible];
    [_selectCuisinesView hidden];
    [_selectOrderView hidden];
}

#pragma 选择商圈信息
- (void)selectCircleFinished:(NSDictionary *)selectedData
{
    NSString *title = [selectedData objectForKey:@"lx_name"];
    _circleId = [selectedData objectForKey:@"id"];
    
    [self.toolButton2 setTitleForNormal:title];
    
    [_dataSource fetchShopWithCuisines:_cuisinesId circle:_circleId order:_orderId isLoadMore:NO];
}

#pragma 弹出排序菜单
- (IBAction)selectOrderAction:(id)sender
{
    [_selectOrderView showOrVisible];
    [_selectCircleView hidden];
    [_selectCuisinesView hidden];
}

#pragma 选择排序信息
- (void)selectOrderFinished:(NSDictionary *)selectedData
{
    NSString *title = [selectedData objectForKey:@"title"];
    _orderId = [selectedData objectForKey:@"book_type"];
    
    [self.toolButton3 setTitleForNormal:title];
    
    [_dataSource fetchShopWithCuisines:_cuisinesId circle:_circleId order:_orderId isLoadMore:NO];
}

#pragma 将分页加载的数据添加到tableview后面
- (void)appendTableWith:(NSMutableArray *)data
{
    for (int i = 0; i < [data count]; i++) {
        [_dataSource.shopList addObject:[data objectAtIndex:i]];
    }
    
    NSMutableArray *insertIndexPaths = [NSMutableArray arrayWithCapacity:10];
    
    for (int ind = 0; ind < [data count]; ind++) {
        NSIndexPath *newPath = [NSIndexPath indexPathForRow:[_dataSource.shopList indexOfObject:[data objectAtIndex:ind]] inSection:0];
        [insertIndexPaths addObject:newPath];
    }
    
    [self.shopTable insertRowsAtIndexPaths:insertIndexPaths withRowAnimation:UITableViewRowAnimationFade];
    
    self.moreLoading = NO;
}

@end

//======================================================================================
#pragma ===================数据源类实现===================================================
//======================================================================================

@implementation ShopListDataSource

#define FETCH_NEW_TAG  1001
#define FETCH_MORE_TAG 1002
#define PAGE_COUNT 5

- (id)initWithVC:(id)viewController
{
    self = [super init];
    if(self) {
        self.viewController = viewController;
        _shopList = [[NSMutableArray alloc] initWithCapacity:10];
    }
    return self;
}

#pragma 获取餐厅信息
- (void)fetchShopWithCuisines:(NSString*)cuisinesId circle:(NSString*)circleId order:(NSString *)orderId isLoadMore:(BOOL)isLoadMore
{
    if (!isLoadMore) [SVProgressHUD show];
    
    //根据是否加载更多判断是加载第一页还是第几页
    self.pageNumber = isLoadMore ? self.pageNumber : 1;
    
    NSString *url = [NSString stringWithFormat:API_SHOP_LIST,[AppSetting longitude],[AppSetting latitude],cuisinesId,S_EMPTY,circleId,orderId,self.pageNumber,[AppSetting cityId]];
    
    [self get:url tag:isLoadMore ? FETCH_MORE_TAG:FETCH_NEW_TAG];
}

- (void)requestFinished:(ASIHTTPRequest *)request
{
    NSDictionary *json = [request.responseData JSONValue];
    
    //从新获取餐厅信息，是取第一页
    if (request.tag == FETCH_NEW_TAG) {
        self.shopList = [json objectForKey:@"data"];
        [self.viewController.shopTable reloadData];
    }

    //分页获取餐厅信息，是加载更多
    if (request.tag == FETCH_MORE_TAG) {
        [self.viewController appendTableWith:[json objectForKey:@"data"]];
    }
    
    [SVProgressHUD dismiss];
}

- (void)requestFailed:(ASIHTTPRequest *)request
{
    _pageNumber--;
    [super requestFailed:request];
}

#pragma ===================加载tableview数据 Begin=============================================

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
 {
     return 100;
 }
 
 - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
 {
     return self.shopList.count;
 }
 
 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
 {
     static NSString *CellIdentifier = @"ShopInfoCell";
     
     ShopInfoCell *cell = (ShopInfoCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
     
     if (cell == nil) {
         
         cell = [[ShopInfoCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
         cell.selectionStyle = UITableViewCellSelectionStyleNone;
         [cell setBackgroundColor:[UIColor clearColor]];
     }
     
     NSDictionary *dic = [self.shopList objectAtIndex:indexPath.row];
     [cell setContent:dic];

     return cell;
}

#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *dic = [self.shopList objectAtIndex:indexPath.row];
    
    NSString *shopId = [dic objectForKey:@"id"];
    
    ShopHomeViewController *shopHomeVC = [[ShopHomeViewController alloc] initWithId:shopId];
    shopHomeVC.parentViewController = self.viewController;
    
    [[AppDelegate sharedInstance] showTabBar:shopHomeVC.tabBarController];
    [AppDelegate sharedInstance].tabBarController.tab_delegate = shopHomeVC;
    [[AppDelegate sharedInstance].tabBarController initButtons];
    [self.viewController.navigationController pushViewController:shopHomeVC animated:YES];
}

#pragma 分页加载
-(void)tableView:(UITableView *)tableView  willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.row == _shopList.count-2) {
        if (!self.viewController.moreLoading) {
            self.pageNumber++;
            
            [self fetchShopWithCuisines:self.viewController.cuisinesId circle:self.viewController.circleId order:self.viewController.orderId isLoadMore:YES];
            
            self.viewController.moreLoading = YES;
        }
    }
}

@end





